package com.example.mygame.service;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridLayout;

import com.example.mygame.pojo.Card;
import com.example.mygame.controller.MainActivity;

import java.util.ArrayList;
import java.util.List;

public class GameMap extends GridLayout {


    public GameMap(Context context) {
        super(context);


        init();
    }

    public GameMap(Context context, AttributeSet attrs) {
        super(context, attrs);


        init();
    }

    public GameMap(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        init();
    }

    private void init(){

        setColumnCount(4);     //一行只有4列

        setBackgroundColor(Color.BLUE);   //一个灰色的背景

        addCards(GetCardWidth(),GetCardWidth());   //向布局中加入卡片

        startGame();


        setOnTouchListener(new OnTouchListener() {

            private float startX,startY,offsetX,offsetY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {


                // 判断用户操作

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        offsetX = event.getX()-startX;
                        offsetY = event.getY()-startY;
                        if (Math.abs(offsetX)>Math.abs(offsetY)) {
                            if (offsetX<-5) {
                                left();
                            }else if (offsetX>5) {
                                right();
                            }
                        }else{
                            if (offsetY<-5) {
                                up();
                            }else if (offsetY>5) {
                                down();
                            }
                        }
                        break;
                }
                return true;
            }
        });
    }

    private void up(){

        boolean flag = false;

        for (int y = 0; y < 4; y++) {//对所有列
            for (int x = 0; x < 4; x++) {
                //检查当前点的右侧是否有非空卡片
                for (int x1 = x+1; x1 < 4; x1++) {
                    if (cardsMap[x1][y].getNum()>0) {//如果右边有非空卡片

                        if (cardsMap[x][y].getNum()<=0) {//当前坐标上没有格子（空卡片和已有卡片合并）


                            cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);

                            x--;

                            flag = true;

                        }else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
                            cardsMap[x1][y].setNum(0);

                            MainActivity.getMainActivity().addScore(cardsMap[x][y].getNum() * 10);
                            flag = true;
                        }
                        break;

                    }
                }
            }
        }
        if (flag) {
            addRandomNum();
            checkComplete();
        }
    }

    private void down(){
        boolean flag = false;

        for (int y = 0; y < 4; y++) {//对所有列
            for (int x = 3; x >= 0; x--) {
                //检查当前点的右侧是否有非空卡片（非空：num>=2）
                for (int x1 = x-1; x1 >= 0; x1--) {
                    if (cardsMap[x1][y].getNum()>0) {//如果右边有非空卡片

                        if (cardsMap[x][y].getNum()<=0) {//当前坐标上没有格子（空卡片和已有卡片合并）


                            cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);

                            x++;//和空卡片合并，还需要从当前位置计算（否则：|0|2|2|2|左移之后变为|2|2|2|0|）
                            flag = true;


                        }else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
                            cardsMap[x1][y].setNum(0);

                            MainActivity.getMainActivity().addScore(cardsMap[x][y].getNum() * 10);
                            flag = true;
                        }
                        break;

                    }
                }
            }
        }
        if (flag) {
            addRandomNum();
            checkComplete();
        }

    }

    private void left(){
        boolean flag = false;
        for (int x = 0; x < 4; x++) {//对所有列
            for (int y = 0; y < 4; y++) {
                //检查当前点的右侧是否有非空卡片（非空：num>=2）
                for (int y1 = y+1; y1 < 4; y1++) {
                    if (cardsMap[x][y1].getNum()>0) {//如果右边有非空卡片

                        if (cardsMap[x][y].getNum()<=0) {//当前坐标上没有格子（空卡片和已有卡片合并）


                            cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);

                            y--;//和空卡片合并，还需要从当前位置计算（否则：|0|2|2|2|左移之后变为|2|2|2|0|）
                            flag = true;
                        }else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
                            cardsMap[x][y1].setNum(0);

                            MainActivity.getMainActivity().addScore(cardsMap[x][y].getNum() * 10);
                            flag = true;
                        }
                        break;

                    }
                }
            }
        }
        if (flag) {
            addRandomNum();
            checkComplete();
        }
    }

    private void right(){
        boolean flag = false;
        for (int x = 0; x < 4; x++) {//对所有列
            for (int y = 3; y >= 0; y--) {
                //检查当前点的右侧是否有非空卡片（非空：num>=2）
                for (int y1 = y-1; y1 >= 0; y1--) {
                    if (cardsMap[x][y1].getNum()>0) {//如果右边有非空卡片

                        if (cardsMap[x][y].getNum()<=0) {//当前坐标上没有格子（空卡片和已有卡片合并）


                            cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);

                            y++;//和空卡片合并，还需要从当前位置计算（否则：|0|2|2|2|左移之后变为|2|2|2|0|）
                            flag = true;
                        }else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
                            cardsMap[x][y1].setNum(0);

                            MainActivity.getMainActivity().addScore(cardsMap[x][y].getNum() * 10);
                            flag = true;
                        }
                        break;

                    }
                }
            }
        }
        if (flag) {
            addRandomNum();
            checkComplete();
        }
    }

    private int GetCardWidth()
    {

        //屏幕信息的对象
        DisplayMetrics displayMetrics;
        displayMetrics = getResources().getDisplayMetrics();

        //获取屏幕信息
        int cardWidth;
        cardWidth = displayMetrics.widthPixels;

        //一行有四个卡片，每个卡片占屏幕的四分之一
        return ( cardWidth - 10 ) / 4;

    }

    private void addCards(int width, int height) {

        Card card;

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                card = new Card(getContext());
                card.setNum(0);
                addView(card,width,height);
                cardsMap[i][j] = card;
            }
        }
    }

    private void startGame() {


        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                cardsMap[i][j].setNum(0);
            }
        }
        addRandomNum();
        addRandomNum();
    }

    void printMap(){
        for (int i = 0; i <4; i++) {
            for (int j = 0; j < 4; j++) {
                System.out.print(cardsMap[i][j].getNum());
            }
            System.out.println();
        }
    }

    private void addRandomNum(){

        // 随机位置添加随机数

        emptyPoints.clear();

        for (int i = 0; i < 4; i++) {

            for (int j = 0; j < 4; j++) {
                if (cardsMap[i][j].getNum() <= 0) {
                    emptyPoints.add(new Point(i,j));
                }
            }
        }

        Point point = emptyPoints.remove((int)(Math.random()*emptyPoints.size()));

        cardsMap[point.x][point.y].setNum(Math.random()>0.1?2:4);


    }
    private void checkComplete() {

        boolean complete = true;

        All: for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {

                // 游戏没有结束的判定情况 5种情况
                if (cardsMap[x][y].getNum() == 0
                        || (x > 0 && cardsMap[x][y].equals(cardsMap[x - 1][y]))
                        || (x < 3 && cardsMap[x][y].equals(cardsMap[x + 1][y]))
                        || (y > 0 && cardsMap[x][y].equals(cardsMap[x][y - 1]))
                        || (y < 3 && cardsMap[x][y].equals(cardsMap[x][y + 1]))) {

                    complete = false;
                    break All; // 写一个标签，跳出所有循环
                }
            }
        }

        if (complete) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
            dialog.setTitle("你好")
                    .setMessage("游戏结束")
                    .setPositiveButton("重来",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    MainActivity.getMainActivity().setScore(0);
                                    startGame();
                                }
                            });

            dialog.setNegativeButton("关闭程序", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.getMainActivity().finish();
                }
            });
            dialog.show();
        }

    }





    private Card[][] cardsMap = new Card[4][4];

    private List<Point> emptyPoints = new ArrayList<Point>();

}
